package lesson.exam;

import com.github.pagehelper.PageInfo;
import lesson.base.BaseServlet;
import lesson.permission.Role;
import lesson.user.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/exam/*")
@Role(User.ROLE_ADMIN)
public class ExamServlet extends BaseServlet {

    private ExamService examService = new ExamService();
    private ExamSubjectService examSubjectService = new ExamSubjectService();
    /**
     * 考试管理的首页
     */
    public void index() {
        forwardJsp("/pages/exam/index");
    }

    /**
     * 考试管理的编辑页面
     */
    public void edit(Integer id) {
        forwardJsp("/pages/exam/edit");
    }

    /**
     * 获取某一次考试的数据
     * @param id
     */
    public void getOne(Integer id) throws ServletException, IOException {
        Exam exam = examService.getById(id);
        List<ExamSubject> subjects = examSubjectService.list(id);
        Map<String, Object> map = new HashMap< >();
        map.put("exam", exam);
        map.put("subjects", subjects);

        writeJSON(true, null, map);

    }

    /**
     * 查询考试
     */
    public void list(String keywords, Integer pageNumber, Integer pageSize) throws ServletException, IOException {
        PageInfo<Exam> list = examService.list(keywords, pageNumber, pageSize);
        writeJSON(true, null, list);
    }

    public void listAll() throws ServletException, IOException {
        writeJSON(true, null, examService.listAllExam());
    }

    /**
     * 删除考试
     * @param id
     */
    public void del(Integer id) throws ServletException, IOException {
        String result = examService.del(id);
        if (result == null) {
            writeJSON(true);
        } else {
            writeJSON(false, result);
        }
    }


    /**
     * 保存考试
     * @param exam
     * @param subjects
     * @throws ServletException
     * @throws IOException
     */
    public void save(Exam exam, List<ExamSubject> subjects) throws ServletException, IOException {
        String result = examService.saveExam(exam, subjects);
        if (result == null) {
            writeJSON(true);
        } else {
            writeJSON(false, result);
        }
    }


    public void listExamGrades(Integer examId) throws ServletException, IOException {

        writeJSON(true, null, examService.listExamGrades(examId));
    }

    public void listExamSubjects(Integer examId, Integer gradeId) throws ServletException, IOException {
        if (examId == null || gradeId == null) {
            writeJSON(false, "请选择年级和考试");
            return;
        }
        writeJSON(true, null, examService.listExamSubjects(examId, gradeId));
    }

}
